import 'dart:io';

import 'package:flutter/material.dart';
import 'package:xindong/utils/xindong_image_util.dart';
import 'package:xindong/utils/xindong_text_util.dart';
import 'package:xindong/widgets/common/xindong_app_bar.dart';
import 'package:xindong/widgets/dialog/xindong_base_alert.dart';
import 'package:xindong/widgets/common/xindong_common_widget.dart';
import 'package:xindong/widgets/video/xindong_common_video_player_layer.dart';
import 'package:xindong/widgets/video/xindong_common_video_player_progress_control.dart';
import 'package:video_player/video_player.dart';

/// 弹窗播放视频
class XinDongVideoPlayerDialog extends StatefulWidget {
  final String? videoUrl;
  final String? coverUrl;
  final File? file;

  const XinDongVideoPlayerDialog({Key? key, this.videoUrl, this.coverUrl, this.file}) : super(key: key);

  // 显示
  XinDongVideoPlayerDialog.show({super.key, this.videoUrl, this.coverUrl, this.file}) {
    showAlertDialog(alert: this);
  }

  @override
  State<XinDongVideoPlayerDialog> createState() => _XinDongVideoPlayerDialogState();
}

class _XinDongVideoPlayerDialogState extends State<XinDongVideoPlayerDialog> {
  late VideoPlayerController _playerController;

  @override
  void initState() {
    super.initState();

    if (!TextUtil.isEmpty(widget.videoUrl)) {
      _playerController = VideoPlayerController.networkUrl(
        Uri(path: widget.videoUrl!),
        videoPlayerOptions: VideoPlayerOptions(mixWithOthers: true),
      );
    }
    if (widget.file != null) {
      _playerController = VideoPlayerController.file(widget.file!);
    }

    _playerController.setLooping(true);
    _playerController.initialize().then((value) {
      _playerController.play();
    });
  }

  @override
  void dispose() {
    _playerController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: GestureDetector(
        onTap: () => Navigator.pop(context),
        behavior: HitTestBehavior.opaque,
        child: Stack(
          fit: StackFit.expand,
          alignment: Alignment.center,
          children: [
            XinDongAppBar("", toolbarHeight: 0, backgroundColor: Colors.transparent),

            // 全屏视频层
            XinDongCommonVideoPlayerBigLayer(
              _playerController,
              cover: videoPlayerCoverLayer(widget.coverUrl),
            ),

            // 进度条
            Positioned(
              left: 0,
              right: 0,
              bottom: 0,
              height: 2.5,
              child: XinDongCommonVideoPlayerProgressControl(videoPlayerController: _playerController),
            ),
          ],
        ),
      ),
    );
  }
}
